package com.hsav.kcxb.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.hsav.kcxb.R;
import com.hsav.kcxb.activity.ClassListActivity;
import com.hsav.kcxb.activity.RecordActivity;
import com.hsav.kcxb.activity.SingerListActivity;
import com.hsav.kcxb.activity.SingerWorkActivity;
import com.hsav.kcxb.adapter.LocalSongsAdapter;
import com.hsav.kcxb.adapter.SingerWorkAdapter;
import com.hsav.kcxb.adapter.SongListAdapter;
import com.hsav.kcxb.main.MSYS;
import com.kcbsdk.AFetchType;
import com.kcbsdk.EventHandler;
import com.kcbsdk.MyRankBa.AObbligStyle;
import com.kcbsdk.MyRankBa.AObbligatoList;
import com.kcbsdk.MyTools.ACloudType;
import com.kcbsdk.MyTools.AUiPageName;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import static com.hsav.kcxb.main.MSYS.MSTRING;
import static com.hsav.kcxb.main.MSYS.mMyRankBa;
import static com.hsav.kcxb.main.MSYS.mMyTools;


/**
 * Created by zhao on 16-12-9.
 */

public class SingFragment extends Fragment implements TabHost.OnTabChangeListener {

    private View mRootView;
    private TextView mTitleTX;
    private SingerWorkAdapter songsAdapter;
    private SingerWorkAdapter selectedSongsAdapter;
    private SingerWorkAdapter localSongsAdapter;
    private Activity mActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.frag_song_layout,container,false);
        initView();
        initData();
        return mRootView;
    }
    public void OnShowWindow(Activity activity, boolean show){
        if (show && mMyRankBa != null && mMyTools != null){
            mActivity = activity;
            mMyRankBa.setUiEventCallBack(activity, new EventHandler() {
                @Override
                public void onComplete(int methodType, boolean isFail, String message) {
                    if (methodType > 0){
                        if (isFail){
                            mMyRankBa.Toast(String.format("%s%s(%08x)", getString(R.string.methodError), message, methodType));
                        }
                        else {
                            if (mMyRankBa.isSucessObbligatoListDbs(methodType, AObbligStyle.OBBLIG_RECOMMEND)) {
                                if (null != mMyRankBa.mAObbligatoList) {
                                    ArrayList<AObbligatoList> list = new ArrayList<>();
                                    for (int counter = 0; counter < mMyRankBa.mAObbligatoList.length; counter++) {
                                        list.add(mMyRankBa.mAObbligatoList[counter]);
//                                        mMyTools.Log(String.format("mAObbligatoList %d %d ", mMyRankBa.mAObbligatoList[counter].MusicID0, mMyRankBa.mAObbligatoList[counter].MusicID1));
                                    }
                                    songsAdapter.setData(list);
                                }
                            }
                        }
                    } else {
//                        mMyRankBa.Log("mMyRankBa.isEventObbligatoListDbs ");
                    }
                }
            });
            mMyTools.setUiEventCallBack(activity, new EventHandler() {
                @Override
                public void onComplete(int methodType, boolean isFail, String message) {
                    if (methodType > 0) {
                        if (isFail) {
                            mMyTools.Toast(String.format("%s%s(%08x)", getString(R.string.methodError), message, methodType));
                        } else {
                        }
                    } else {
                        if (mMyTools.isEventLocalInfoDbs(ACloudType.TYPE_KBA, AUiPageName.PAGE_DOWN_OBBLIG)){
                            if (mMyTools.mAObbligaList != null) {
                                mMyTools.Log("isEventLocalInfoDbs PAGE_DOWN_OBB "+ mMyTools.mAObbligaList.length);
                               // ArrayList<AObbligatoList> list = CreateSimpleData();


                                ArrayList<AObbligatoList> list = new ArrayList<>();

                                for (int counter = 0; counter < mMyTools.mAObbligaList.length; counter++) {
                                    //MSYS_DEC(mMyTools.mAObbligaList[counter].ItemID);MSTRING(mMyTools.mAObbligaList[counter].SongName);
                                    mMyTools.Log("  "+mMyTools.mAObbligaList[counter].SongName + "  "+mMyTools.mAObbligaList[counter].ArtistName);//MSYS_DEC(mMyTools.mAObbligaList[counter].FileLength);

                                    AObbligatoList item = new AObbligatoList();
                                    item.SongName = mMyTools.mAObbligaList[counter].SongName;
                                    item.ArtistName = mMyTools.mAObbligaList[counter].SongIntro;
                                    item.FileSize = mMyTools.mAObbligaList[counter].FileSize;
//                                    item.IconFile = mMyTools.mAObbligaList[counter].CoverFile;
                                    list.add(item);
                                }

                                selectedSongsAdapter.setData(list);
                            }
                        }
                        if (mMyTools.isEventLocalInfoDbs(ACloudType.TYPE_KBA, AUiPageName.PAGE_UP_RECORD)){
                            mMyTools.Log("isEventLocalInfoDbs B");
                        }
                        if (mMyTools.isEventLocalInfoDbs(ACloudType.TYPE_KBA, AUiPageName.PAGE_DOWN_OBBLIG)){
                            MSTRING("PAGE_DOWN_OBBLIG B");
                        }
                    }
                }
            });
            mMyRankBa.fetchObbligatoListDbs(AFetchType.LIST_NORMAL, AObbligStyle.OBBLIG_RECOMMEND, "");
        }
    }

    private void initData() {
    }
    private void initView() {
        mTitleTX = (TextView)mRootView.findViewById(R.id.tv_top_title);
        mTitleTX.setText("查找歌曲");
        TabHost tabHostTop = (TabHost) mRootView.findViewById(R.id.tab_host_top);
        tabHostTop.setup();
        tabHostTop.addTab(tabHostTop.newTabSpec("tab1").setContent(R.id.tab1).setIndicator("k吧"));
        tabHostTop.addTab(tabHostTop.newTabSpec("tab2").setContent(R.id.tab2).setIndicator("唱吧"));
        tabHostTop.addTab(tabHostTop.newTabSpec("tab3").setContent(R.id.tab3).setIndicator("好唱"));
        tabHostTop.addTab(tabHostTop.newTabSpec("tab4").setContent(R.id.tab4).setIndicator("爱唱"));

        TabHost tabHostKB = (TabHost) mRootView.findViewById(R.id.tab_host_kb);
        tabHostKB.setup();
        tabHostKB.addTab(tabHostTop.newTabSpec("tab1").setContent(R.id.tab1_1).setIndicator("点歌台"));
        tabHostKB.addTab(tabHostTop.newTabSpec("tab2").setContent(R.id.tab2_1).setIndicator("已点歌曲"));
        tabHostKB.addTab(tabHostTop.newTabSpec("tab3").setContent(R.id.tab3_1).setIndicator("本地录音"));
        tabHostKB.addTab(tabHostTop.newTabSpec("tab4").setContent(R.id.tab3_1).setIndicator("手机伴奏"));
        tabHostKB.setOnTabChangedListener(this);

        ListView mListViewSongs = (ListView)mRootView.findViewById(R.id.list_view_songs);
        songsAdapter = new SingerWorkAdapter(getActivity());
        mListViewSongs.setAdapter(songsAdapter);

        View mViewStar = mRootView.findViewById(R.id.view_star);
        mViewStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SingerListActivity.class);
                startActivity(intent);
            }
        });

        View mViewClass = mRootView.findViewById(R.id.view_class);
        mViewClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ClassListActivity.class);
                startActivity(intent);
            }
        });

        View mViewSolo = mRootView.findViewById(R.id.view_solo);
        mViewSolo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), RecordActivity.class));
            }
        });

        View mViewChorus = mRootView.findViewById(R.id.view_chorus);
        mViewChorus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), RecordActivity.class));
            }
        });

        View textViewMore = mRootView.findViewById(R.id.text_view_more);
        textViewMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SingerWorkActivity.startWithFilterRecommend(getContext());
            }
        });

        ListView listSelectedSongs = (ListView) mRootView.findViewById(R.id.list_songs_selected);
        selectedSongsAdapter = new SingerWorkAdapter(getActivity());
        listSelectedSongs.setAdapter(selectedSongsAdapter);

        ListView listLocalSongs = (ListView) mRootView.findViewById(R.id.list_songs_local);
        localSongsAdapter = new SingerWorkAdapter(getActivity());
        listLocalSongs.setAdapter(localSongsAdapter);
    }

    private ArrayList<AObbligatoList> CreateSimpleData() {
        ArrayList<AObbligatoList> list = new ArrayList<>();

        AObbligatoList item = new AObbligatoList();
        item.ArtistName = "张";
        item.FileSize = 3048000;
        item.SongName = "离歌";
        list.add(item);

        item = new AObbligatoList();
        item.ArtistName = "李";
        item.FileSize = 3056000;
        item.SongName = "嗨歌";
        list.add(item);
        return list;
    }

    @Override
    public void onTabChanged(String tabId) {
        //mMyTools.Log("onTabChanged "+tabId);
       // Toast.makeText(getActivity(), String.format("Tab changed.(%s)", tabId), Toast.LENGTH_SHORT).show();
        OnShowWindow(mActivity, true);
        if ("tab1".equals(tabId)){              // 点歌台
            mMyRankBa.fetchObbligatoListDbs(AFetchType.LIST_FRESHEN, AObbligStyle.OBBLIG_RECOMMEND, "");
        }
        else if ("tab2".equals(tabId))  {       // 已点歌曲
            MSTRING("PAGE_DOWN_OBBLIG A");
            mMyTools.fetchLocalInfoDbs(ACloudType.TYPE_KBA, AUiPageName.PAGE_DOWN_OBBLIG);
        }
        else if ("tab3".equals(tabId)) {         // 本地录音
            mMyTools.fetchLocalInfoDbs(ACloudType.TYPE_KBA, AUiPageName.PAGE_UP_RECORD);
        }
        else  {                                     // 手机伴奏
            // "
            //mMyTools.fetchLocalInfoDbs(ACloudType.TYPE_KBA, AUiPageName.PAGE_UP_RECORD);

//            String path1 = getInnerSDCardPath();
//            List<String> extPaths = getExtSDCardPath(true);
//            String paths = "";
//            for (String path : extPaths) {
//                if (!path.equals(path1)) {
//                    paths += path + ",";
//                }
//            }
//            String paths="/storage/emulated/,";
            String paths="/storage/emulated/0/,";
//            http://www.jb51.net/article/100999.htm
            mMyTools.Log("SD卡路径：" + paths);
//            if (!"".equals(paths)) {
                //mMyTools.searchLocalSpecFileDbs(ACloudType.TYPE_KBA, AFetchType.LIST_FRESHEN, AUiPageName.PAGE_LOCAL_OBBLIGA, paths);
            File file = new File("/storage/emulated/0/");
            search(file);
//                //内置sd卡路径
//                String sdcardPath = System.getenv("EXTERNAL_STORAGE");
////内置sd卡路径
//                String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
////外置置sd卡路径
//                String extSdcardPath = System.getenv("SECONDARY_STORAGE");
//                在Enviroment类的源码中获得sd卡路径其实也是通过 System.getnv() 方法来实现的，如隐藏的方法:
//
///** {@hide} */
//
//            }

        }
    }

    private void search(File fileold)
    {
        try{
mMyTools.Log("search A ");
            File[] files=fileold.listFiles();
mMyTools.Log("search B "+ files.length);
            if(files.length>0)
            {
mMyTools.Log("search C ");
                for(int j=0;j<files.length;j++)
                {
                    if(!files[j].isDirectory())
                    {
//                        if(files[j].getName().indexOf(key)> -1 || files[j].getName().indexOf(key2)> -1)
//                        {
//                            SelectFileInfo info = new SelectFileInfo();
//                            info.setAvatar("");
//                            info.setName(files[j].getName());
//                            info.setFilePath(files[j].getPath());
//                            info.setSize(MSYS.SetAmountStringByte(files[j].length()));
//                            mHomeDomainInfo.add(info);
//                        }
                        mMyTools.Toast("A "+files[j]);
                    }
                    else{
                        this.search(files[j]);
                    }
                }
            }
        }
        catch(Exception e)
        {

        }
    }


    public String getInnerSDCardPath() {

        return Environment.getExternalStorageDirectory().getPath();
    }
    public final static String Tab_ExtSDCardPath[] = {
            "extSdCard", "/mnt/", "/data/", "/dev/",
    };
    public List<String> getExtSDCardPath(boolean show){
        List<String> lResult = new ArrayList<String>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            String path;
            String[] params;
            while ((line = br.readLine()) != null) {
                if (show) {
                    mMyTools.Log("getExtSDCardPath A " + line);
                }
                for (int tabCou = 0; tabCou < Tab_ExtSDCardPath.length; tabCou++){
                    if (line.contains(Tab_ExtSDCardPath[tabCou])) {
                        params = line.split(" ");
                        for (int counter = 0; counter < params.length; counter++) {
                            path = params[counter];
                            if (path.length() > 8) {
                                if (show) {
                                    //   mMyTools.Log("getExtSDCardPath B " + path);
                                }
                                File file = new File(path);
                                if (file.isDirectory()) {
                                    if (show) {
                                        mMyTools.Log("getExtSDCardPath 加入 " + path);
                                    }
                                    lResult.add(path);
                                }
                            }
                        }
                    }
                }
            }
            isr.close();
        } catch (Exception e) {
        }
        return lResult;
    }

    public static Map<String, File> getAllStorageLocations() {
        Map<String, File> map = new HashMap<String, File>(10);

        List<String> mMounts = new ArrayList<String>(10);
        List<String> mVold = new ArrayList<String>(10);
        mMounts.add("/mnt/sdcard");
        mVold.add("/mnt/sdcard");

        try {
            File mountFile = new File("/proc/mounts");
            if (mountFile.exists()) {
                Scanner scanner = new Scanner(mountFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("/dev/block/vold/")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[1];

                        // don't add the default mount path
                        // it's already in the list.
                        if (!element.equals("/mnt/sdcard"))
                            mMounts.add(element);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            File voldFile = new File("/system/etc/vold.fstab");
            if (voldFile.exists()) {
                Scanner scanner = new Scanner(voldFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("dev_mount")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[2];

                        if (element.contains(":"))
                            element = element.substring(0, element.indexOf(":"));
                        if (!element.equals("/mnt/sdcard"))
                            mVold.add(element);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        for (int i = 0; i < mMounts.size(); i++) {
            String mount = mMounts.get(i);
            if (!mVold.contains(mount))
                mMounts.remove(i--);
        }
        mVold.clear();

        List<String> mountHash = new ArrayList<String>(10);

//        for (String mount : mMounts) {
//            File root = new File(mount);
//            if (root.exists() && root.isDirectory() && root.canWrite()) {
//                File[] list = root.listFiles();
//                String hash = "[";
//                if (list != null) {
//                    for (File f : list) {
//                        hash += f.getName().hashCode() + ":" + f.length() + ", ";
//                    }
//                }
//                hash += "]";
//                if (!mountHash.contains(hash)) {
//                    String key = SD_CARD + "_" + map.size();
//                    if (map.size() == 0) {
//                        key = SD_CARD;
//                    } else if (map.size() == 1) {
//                        key = EXTERNAL_SD_CARD;
//                    }
//                    mountHash.add(hash);
//                    map.put(key, root);
//                }
//            }
//        }
//        mMounts.clear();
//        if (map.isEmpty()) {
//            map.put(SD_CARD, Environment.getExternalStorageDirectory());
//        }
        return map;
    }
}
